package com.nq.utils.email;


import cn.hutool.core.date.DateUtil;
import com.nq.common.LoginType;
import com.nq.common.SystemVersionEnum;
import com.nq.dao.SmsLogMapper;
import com.nq.dao.fund.StFundMapper;
import com.nq.fund.entity.StFund;
import com.nq.pojo.*;
import com.nq.service.ISiteSmsLogService;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.DateUtils;
import com.nq.utils.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.init.ResourceReader;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class SendHTMLMail {
    private static final Logger log = LoggerFactory.getLogger(SendHTMLMail.class);

    @Autowired(required = false)
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String userName;

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${spring.mail.emailPath}")
    private String emailPath;

    @Resource
    SmsLogMapper smsLogMapper;

    @Resource
    ISiteSmsLogService siteSmsLogService;

    @Resource
    StFundMapper stFundMapper;

    /**
     * 忘记密码，发送邮箱
     * @param email
     */
    public boolean sendForgetEmail(String email, String verificationCode){

        try {
            log.info("用户忘记密码发送邮箱验证码开始， email：{}", email);
            if (StringUtils.isBlank(email)) {
                return false;
            }

            MimeMessage message = mailSender.createMimeMessage();
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 邮箱标题
            String subject = "Forgot the password verification code";

            //邮箱发送者
            helper.setFrom(userName);
            //收件人，可以为多个收件人，收件人之间用逗号隔开
            helper.setTo(email);
            helper.setSubject(subject);

            String spliceTemplate = this.forgetTemplate(verificationCode);
            // 邮箱内容
            helper.setText(spliceTemplate, true);
            mailSender.send(message);
            // 保存邮箱验证码数据
            saveSiteSmsLog(email, LoginType.EMAIL.getCode(), verificationCode, "Forgot password");
            return true;
        }catch (Exception e) {
            log.error("用户忘记密码时发送邮件提醒失败", e.getMessage());
            e.printStackTrace();
        }
        log.info("用户忘记密码发送邮件提醒结束， email：{}", email);
        return false;
    }

    private String forgetTemplate(String verificationCode) {
        SAXReader reader = new SAXReader();
        Document document = null;
        String path = emailPath + "forgetEmail.html";
        try {

            document = reader.read(path);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            // 验证码
            if (StringUtils.isNotBlank(verificationCode)) {
                Element element = splitNodes(root, "id", "verificationCodeId");
                element.setText(verificationCode);
            }

            FileWriter fwriter = new FileWriter(path);
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();
            fwriter.close();

            FileReader in = new FileReader(path);
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);
            str = str.replaceAll("\000", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 用户注册发送邮箱验证码
     * @param email
     */
    public boolean sendRegEmail(String email, String verificationCode){

        try {
            log.info("用户注册发送邮箱验证码开始， email：{}", email);
            if (StringUtils.isBlank(email)) {
                return false;
            }

            MimeMessage message = mailSender.createMimeMessage();
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 邮箱标题
            String subject = "Registration verification code";

            //邮箱发送者
            helper.setFrom(userName);
            //收件人，可以为多个收件人，收件人之间用逗号隔开
            helper.setTo(email);
            helper.setSubject(subject);

            String spliceTemplate = this.regTemplate(verificationCode);
            // 邮箱内容
            helper.setText(spliceTemplate, true);
            mailSender.send(message);
            // 保存邮箱验证码数据
            saveSiteSmsLog(email, LoginType.EMAIL.getCode(), verificationCode, "register");
            return true;
        }catch (Exception e) {
            log.error("用户发送交易行为时发送邮件提醒失败", e.getMessage());
        }

        log.info("用户注册发送邮箱验证码结束， email：{}", email);
        return false;
    }

    private String regTemplate(String verificationCode) {
        SAXReader reader = new SAXReader();
        Document document = null;
        String path = emailPath + "regEmail.html";
        try {
            document = reader.read(path);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            // 用户名称
            if (StringUtils.isNotBlank(verificationCode)) {
                Element element = splitNodes(root, "id", "verificationCodeId");
                element.setText(verificationCode);
            }


            FileWriter fwriter = new FileWriter(path);
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();

            FileReader in = new FileReader(path);
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\000", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 用户发送交易行为时发送邮件提醒
     * @param user
     * @param positionDetail 交易详情
     */
    @Async
    public void sendTradingBehaviorEmail(User user, UserPositionDetail positionDetail){

        String spliceTemplate = "";
        try {
            log.info("用户发送交易行为时发送邮件提醒开始， User：{}", user.getId());

            String email = user.getEmail();
            if (StringUtils.isBlank(email)) {
                log.error("获取用户邮箱失败， User：{}", user.getId());
                return;
            }

            MimeMessage message = mailSender.createMimeMessage();
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 邮箱标题
            String subject = "Subject: Trade Confirmation for AAPL - " + DateUtils.getDate("yyyy/MM/dd");

            //邮箱发送者
            helper.setFrom(userName);
            //收件人，可以为多个收件人，收件人之间用逗号隔开
            helper.setTo(email);
            helper.setSubject(subject);

            spliceTemplate = this.spliceTemplate(user, positionDetail);
            // 邮箱内容
            helper.setText(spliceTemplate, true);
            mailSender.send(message);
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, "success");
        }catch (Exception e) {
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, e.getMessage());
            log.error("用户发送交易行为时发送邮件提醒失败", e.getMessage());
        }

        log.info("用户发送交易行为时发送邮件提醒结束， User：{}", user.getId());
    }

    private String spliceTemplate(User user, UserPositionDetail positionDetail){
        SAXReader reader = new SAXReader();
        Document document = null;
        String path = emailPath + "trading.html";
        try {
            document = reader.read(path);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            // 用户名称
            String realName = user.getRealName();
            if (StringUtils.isNotBlank(realName)) {
                Element noticeName = splitNodes(root, "id", "realName");
                noticeName.setText(realName);
            }else {
                String nickName = user.getNickName();
                Element noticeName = splitNodes(root, "id", "realName");
                noticeName.setText(nickName);
            }
            // 订单时间
            Date orderTime = positionDetail.getOrderTime();
            Element orderTimeEle = splitNodes(root, "id", "orderTime");
            orderTimeEle.setText(DateTimeUtil.dateToStr(orderTime));
            // 股票代码
            Element stockCode = splitNodes(root, "id", "stockCode");
            stockCode.setText(positionDetail.getStockCode());
            // 股票名称
            Element stockName = splitNodes(root, "id", "stockName");
            stockName.setText(positionDetail.getStockName());
            // 买卖类型
            Element stockType = splitNodes(root, "id", "stockType");
            Integer type = positionDetail.getType();
            if (type == 1) {
                stockType.setText("Buy");
            }else {
                stockType.setText("Sell");
            }
            // 订单数量
            Element orderNum = splitNodes(root, "id", "orderNum");
            orderNum.setText(positionDetail.getOrderNum().toString() + " Shares");
            // 交易金额
            Element orderPrice = splitNodes(root, "id", "orderPrice");
            BigDecimal price = positionDetail.getOrderPrice();
            String stockGid = positionDetail.getStockGid();
//            if (SystemVersionEnum.india.name().equals(active)){
//                orderPrice.setText("₹" + price);
//            }else {
//                orderPrice.setText("$" + price);
//            }
            orderPrice.setText("₫" + price);
            // 订单总金额
            Element orderTotalPrice = splitNodes(root, "id", "orderTotalPrice");
            BigDecimal totalPrice = positionDetail.getOrderTotalPrice();
//            if (SystemVersionEnum.india.name().equals(active)){
//                orderTotalPrice.setText("₫" + totalPrice);
//            }else {
//                orderTotalPrice.setText("$" + totalPrice);
//            }
            orderTotalPrice.setText("₫" + totalPrice);

            // 佣金指的是手续费，印花税，等
            BigDecimal commission = new BigDecimal(BigInteger.ZERO);
            commission = commission.add(positionDetail.getOrderFee())
                    .add(positionDetail.getOrderSpread())
                    .add(positionDetail.getOrderStayFee())
                    .add(positionDetail.getSpreadRatePrice());
            Element commissionEle = splitNodes(root, "id", "commission");
//            if (stockGid.equals("SH") || stockGid.equals("SZ")){
//                commissionEle.setText("₹" + commission);
//            }else {
//                commissionEle.setText("$" + commission);
//            }
            commissionEle.setText("₫" + commission);

            // 净额指的是订单总金额减去佣金
            BigDecimal netAmount = totalPrice.subtract(commission);
            Element netAmountEle = splitNodes(root, "id", "netAmount");
//            if (SystemVersionEnum.india.name().equals(active)){
//                netAmountEle.setText("₹" + netAmount);
//            }else {
//                netAmountEle.setText("$" + netAmount);
//            }
            netAmountEle.setText("₫" + netAmount);

            // 账号
            Element userId = splitNodes(root, "id", "userId");
            // 格式化时间为 "09:30 AM" 格式
            userId.setText(user.getId().toString());

            // 交易时间
            Element order24Hours = splitNodes(root, "id", "order24Hours");
            // 格式化时间为 "09:30 AM" 格式
            order24Hours.setText(DateUtil.format(orderTime, "hh:mm"));
            // 交易所
            Element stockGidEle = splitNodes(root, "id", "stockGid");
            stockGidEle.setText(stockGid);


            FileWriter fwriter = new FileWriter(path);
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();

            FileReader in = new FileReader(path);
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\000", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }



    public static void main(String[] args) {
        Date now = new Date();

        SimpleDateFormat formatter24 = new SimpleDateFormat("HH:mm");
        SimpleDateFormat formatter12 = new SimpleDateFormat("hh:mm a", Locale.ENGLISH); // 'a' for AM/PM

        String time24 = formatter24.format(now);
        String time12 = formatter12.format(now);

        System.out.println("24-hour format: " + time24);
        System.out.println("12-hour format: " + time12);
    }

    /**
     * 充值成功发送邮箱
     * @param user
     * @param userRecharge 充值信息
     */
    @Async
    public void sendRechargeEmail(User user, UserRecharge userRecharge){
        String spliceTemplate = "";
        try {
            log.info("充值成功时发送邮件提醒开始， User：{}", user.getId());

            String email = user.getEmail();
            if (StringUtils.isBlank(email)) {
                log.error("获取用户邮箱失败， User：{}", user.getId());
                return;
            }

            MimeMessage message = mailSender.createMimeMessage();
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 邮箱标题
            String subject = "Subject: Trade Confirmation for AAPL - " + DateUtils.getDate("yyyy/MM/dd");

            //邮箱发送者
            helper.setFrom(userName);
            //收件人，可以为多个收件人，收件人之间用逗号隔开
            helper.setTo(email);
            helper.setSubject(subject);

            spliceTemplate = this.rechargeTemplate(user, userRecharge);
            // 邮箱内容
            helper.setText(spliceTemplate, true);
            mailSender.send(message);
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, "success");
        }catch (Exception e) {
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, e.getMessage());
            log.error("充值成功时发送邮件提醒失败", e.getMessage());
        }

        log.info("充值成功时发送邮件提醒结束， User：{}", user.getId());
    }

    /**
     * 充值模板
     * @param user
     * @param userRecharge
     * @return
     */
    private String rechargeTemplate(User user, UserRecharge userRecharge){
        SAXReader reader = new SAXReader();
        Document document = null;
        String path = emailPath + "recharge.html";

        try {
            document = reader.read(path);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            // 用户名称
            String realName = user.getRealName();
            if (StringUtils.isNotBlank(realName)) {
                Element noticeName = splitNodes(root, "id", "realName");
                noticeName.setText(realName);
            }
            // 充值时间
            Date time = userRecharge.getPayTime();
            Element timeEle = splitNodes(root, "id", "time");
            timeEle.setText(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
            // 充值金额
            BigDecimal amount = userRecharge.getPayAmt();
            Element amountEle = splitNodes(root, "id", "amount");
//            if (active.equals("india")){
//                amountEle.setText("₹" + amount);
//            }else {
//                amountEle.setText("$" + amount);
//            }
            amountEle.setText("₫" + amount);
            // 账号
            Element userIdEle = splitNodes(root, "id", "userId");
            userIdEle.setText(user.getId().toString());
            // 账户余额
//            if (active.equals("india")){
//                amountEle.setText("₹" + user.getEnableAmt());
//            }else {
//                amountEle.setText("$" + user.getEnableAmt());
//            }
            amountEle.setText("₫" + user.getEnableAmt());
            FileWriter fwriter = new FileWriter(path);
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();

            FileReader in = new FileReader(path);
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\000", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 提现成功发送邮箱
     * @param user
     * @param userWithdraw 提现信息
     */
    @Async
    public void sendWithdrawEmail(User user, UserWithdraw userWithdraw){
        String spliceTemplate = "";
        try {
            log.info("提现成功时发送邮件提醒开始， User：{}", user.getId());

            String email = user.getEmail();
            if (StringUtils.isBlank(email)) {
                log.error("获取用户邮箱失败， User：{}", user.getId());
                return;
            }

            MimeMessage message = mailSender.createMimeMessage();
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 邮箱标题
            String subject = "Subject: Trade Confirmation for AAPL - " + DateUtils.getDate("yyyy/MM/dd");

            //邮箱发送者
            helper.setFrom(userName);
            //收件人，可以为多个收件人，收件人之间用逗号隔开
            helper.setTo(email);
            helper.setSubject(subject);

            spliceTemplate = this.withdrawTemplate(user, userWithdraw);
            // 邮箱内容
            helper.setText(spliceTemplate, true);
            mailSender.send(message);
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, "success");
        }catch (Exception e) {
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, e.getMessage());
            log.error("提现成功时发送邮件提醒失败", e.getMessage());
        }

        log.info("提现成功时发送邮件提醒结束， User：{}", user.getId());
    }

    /**
     * 提现模板
     * @param user
     * @param userWithdraw
     * @return
     */
    private String withdrawTemplate(User user, UserWithdraw userWithdraw){
        SAXReader reader = new SAXReader();
        Document document = null;
        String path = emailPath + "withdraw.html";

        try {
            document = reader.read(path);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            // 用户名称
            String realName = user.getRealName();
            if (StringUtils.isNotBlank(realName)) {
                Element noticeName = splitNodes(root, "id", "realName");
                noticeName.setText(realName);
            }
            // 提现时间
            Date time = userWithdraw.getTransTime();
            Element timeEle = splitNodes(root, "id", "time");
            timeEle.setText(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
            // 提现金额
            BigDecimal amount = userWithdraw.getWithAmt();
            Element amountEle = splitNodes(root, "id", "amount");
//            if (active.equals("india")){
//                amountEle.setText("₹" + amount);
//            }else {
//                amountEle.setText("$" + amount);
//            }
            amountEle.setText("₫" + amount);

            // 账号
            Element userIdEle = splitNodes(root, "id", "userId");
            userIdEle.setText(user.getId().toString());

            FileWriter fwriter = new FileWriter(path);
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();

            FileReader in = new FileReader(path);
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\000", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 基金交易发送邮箱
     * @param user
     * @param fundApplyDetail 基金交易信息
     */
    @Async
    public void sendFundEmail(User user, StFundApplyDetail fundApplyDetail){
        String spliceTemplate = "";
        try {
            log.info("基金交易成功时发送邮件提醒开始， User：{}", user.getId());

            String email = user.getEmail();
            if (StringUtils.isBlank(email)) {
                log.error("获取用户邮箱失败， User：{}", user.getId());
                return;
            }

            MimeMessage message = mailSender.createMimeMessage();
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 邮箱标题
            String subject = "Subject: Trade Confirmation for Fund - " + DateUtils.getDate("MM/dd/yyyy");

            //邮箱发送者
            helper.setFrom(userName);
            //收件人，可以为多个收件人，收件人之间用逗号隔开
            helper.setTo(email);
            helper.setSubject(subject);

            spliceTemplate = this.fundTemplate(user, fundApplyDetail);
            // 邮箱内容
            helper.setText(spliceTemplate, true);
            mailSender.send(message);
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, "success");
        }catch (Exception e) {
            // 保存通知记录
            saveSmsLog(user.getId(), user.getEmail(), spliceTemplate, 2, e.getMessage());
            log.error("基金交易成功时发送邮件提醒失败", e.getMessage());
        }

        log.info("基金交易成功时发送邮件提醒结束， User：{}", user.getId());
    }

    /**
     * 基金交易模板
     * @param user
     * @param fundApplyDetail
     * @return
     */
    private String fundTemplate(User user, StFundApplyDetail fundApplyDetail){
        SAXReader reader = new SAXReader();
        Document document = null;
        String path = emailPath + "fund.html";

        try {
            document = reader.read(path);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            // 用户名称
            String realName = user.getRealName();
            if (StringUtils.isNotBlank(realName)) {
                Element noticeName = splitNodes(root, "id", "realName");
                noticeName.setText(realName);
            }else {
                String nickName = user.getNickName();
                Element noticeName = splitNodes(root, "id", "realName");
                noticeName.setText(nickName);
            }

            // 交易时间
            Date addTime = fundApplyDetail.getAddTime();
            if (null != addTime) {
                Element tradeDate = splitNodes(root, "id", "tradeDate");
                tradeDate.setText(DateUtils.formatDate(addTime, "MM/dd/yyyy"));
            }

            // 基金代码
            StFund stFund =  stFundMapper.selectById(fundApplyDetail.getFundId());
            String fundCode = stFund.getFundCode();
            Element fundCodeEle = splitNodes(root, "id", "stockSymbol");
            fundCodeEle.setText(fundCode);

            // 基金类型，是否有封闭期
            Integer closed = stFund.getClosed();
            Element closedEle = splitNodes(root, "id", "fundType");
            closedEle.setText(closed.intValue() == 1 ? "Closed-End (" + stFund.getClosedDay() +" days)" : "Open-End");

            // 操作
            Integer tradeType = fundApplyDetail.getTradeType();
            Element actionEle = splitNodes(root, "id", "action");
            actionEle.setText(tradeType == 0 ? "Subscription" : "Redemption");

            // 操作2
            Element action2Ele = splitNodes(root, "id", "action2");
            action2Ele.setText(tradeType == 0 ? "Subscription Amount" : "Redemption Amount");

            // 金额
            Element amountEle = splitNodes(root, "id", "amount");
            amountEle.setText("$" + fundApplyDetail.getPurchaseAmount());

            // Front-End Load
            Element frontEle = splitNodes(root, "id", "frontEndLoad");
            frontEle.setText(fundApplyDetail.getFrontEndLoad().multiply(new BigDecimal("100")).setScale(2, 4) + "%");

            // Back-End Load
            Element backEle = splitNodes(root, "id", "backEndLoad");
            backEle.setText(fundApplyDetail.getBackEndLoad().multiply(new BigDecimal("100")).setScale(2, 4) + "%");

            // Management Fee
            Element managementEle = splitNodes(root, "id", "managementFee");
            managementEle.setText(fundApplyDetail.getManagementFee().multiply(new BigDecimal("100")).setScale(2, 4) + "%");

            // 12b-1 Fee
            Element twelveEle = splitNodes(root, "id", "twelveFee");
            twelveEle.setText(fundApplyDetail.getTwelveFee().multiply(new BigDecimal("100")).setScale(2, 4) + "%");

            FileWriter fwriter = new FileWriter(path);
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();

            FileReader in = new FileReader(path);
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\000", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }



    public void send(User user, UserRecharge userRecharge, String emailToken, String host, String emailTo) {
        SAXReader reader = new SAXReader();
        Document document = null;
        InputStream inputStream = ResourceReader.class.getClassLoader().getResourceAsStream("email/auth.html");
        try {
            document = reader.read(inputStream);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            Element time = getNodes(root, "id", "time");
            Calendar calendar = Calendar.getInstance();
            time.setText(calendar
                    .get(1) + "-" + (calendar.get(2) + 1) + "-" + calendar
                    .get(5) + " " + calendar.get(10) + ":" + calendar
                    .get(12) + ":" + calendar.get(13));

            Element noticeName = getNodes(root, "id", "noticeName");
            noticeName.setText(user.getRealName());

            Element userid = getNodes(root, "id", "userid");
            userid.setText(user.getId() + "");
            Element realname = getNodes(root, "id", "realname");
            realname.setText((user.getAccountType().intValue() == 0) ? ("正式用戶 - " + user
                    .getRealName()) : ("模擬用戶 - " + user
                    .getRealName()));
            Element amt = getNodes(root, "id", "amt");
            amt.setText(userRecharge.getPayAmt().toString());
            Element ordersn = getNodes(root, "id", "ordersn");
            ordersn.setText(userRecharge.getOrderSn());

            String authurl = PropertiesUtil.getProperty("site.email.auth.url");

            String emailUrl = host + authurl + "?token=" + emailToken + "&orderSn=" + userRecharge.getOrderSn() + "&state=";

            String successUrl = emailUrl + '\001';
            Element dosuccessurl = getNodes(root, "id", "dosuccessurl");
            dosuccessurl.setText(successUrl);
            Element dosuccess = getNodes(root, "id", "dosuccess");
            dosuccess.setAttributeValue("href", successUrl);

            String failUrl = emailUrl + '\002';
            Element dofailurl = getNodes(root, "id", "dofailurl");
            dofailurl.setText(failUrl);
            Element dofail = getNodes(root, "id", "dofail");
            dofail.setAttributeValue("href", failUrl);

            String cancelUrl = emailUrl + '\003';
            Element docancelurl = getNodes(root, "id", "docancelurl");
            docancelurl.setText(cancelUrl);
            Element docancel = getNodes(root, "id", "docancel");
            docancel.setAttributeValue("href", cancelUrl);

            FileWriter fwriter = new FileWriter(inputStream.toString());
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();

            FileReader in = new FileReader(inputStream.toString());
            char[] buff = new char[10240];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\000", "");
            (new MailSender.Builder(str.toString(), emailTo)).send();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Element splitNodes(Element node, String attrName, String attrValue) {
        List<Attribute> listAttr = node.attributes();
        for (Attribute attr : listAttr) {
            String name = attr.getName();
            String value = attr.getValue();

            if (attrName.equals(name) && attrValue.equals(value)) {
                return node;
            }
        }

        List<Element> listElement = node.elements();
        for (Element e : listElement) {
            Element temp = getNodes(e, attrName, attrValue);

            if (temp != null) {
                return temp;
            }
        }
        return null;
    }

    public Element getNodes(Element node, String attrName, String attrValue) {
        List<Attribute> listAttr = node.attributes();
        for (Attribute attr : listAttr) {
            String name = attr.getName();
            String value = attr.getValue();

            if (attrName.equals(name) && attrValue.equals(value)) {
                return node;
            }
        }

        List<Element> listElement = node.elements();
        for (Element e : listElement) {
            Element temp = getNodes(e, attrName, attrValue);

            if (temp != null) {
                return temp;
            }
        }
        return null;
    }

    /**
     * 保存验证码数据
     */
    public void saveSiteSmsLog(String email, String type, String value, String smsTitle){
        SiteSmsLog siteSmsLog = new SiteSmsLog();
        siteSmsLog.setSmsPhone(email);
        siteSmsLog.setSmsTitle(smsTitle);
        siteSmsLog.setSmsCnt(value);
        siteSmsLog.setSmsStatus(Integer.valueOf(0));
        siteSmsLog.setSmsTemplate("字段无用");
        siteSmsLog.setType(type);
        siteSmsLog.setAddTime(DateTimeUtil.getCurrentDate());
        siteSmsLogService.addData(siteSmsLog);
    }

    /**
     * 保存通知信息
     * @param userId
     * @param phoneOrEmail
     * @param content
     * @param type
     * @param result
     */
    private void saveSmsLog(Integer userId, String phoneOrEmail, String content, Integer type, String result) {
        SmsLog smsLog = new SmsLog();
        smsLog.setUserId(userId);
        smsLog.setPhone(phoneOrEmail);
        smsLog.setContent(content);
        smsLog.setType(type);
        smsLog.setResult(result);
        smsLog.setCreatedAt(new Date());
        smsLogMapper.insert(smsLog);
    }

}
